package com.springcloud.eshop.inventory.service.impl;

import com.alibaba.fastjson.JSON;
import com.springcloud.eshop.inventory.entity.ProductInventory;
import com.springcloud.eshop.inventory.mapper.ProductInventoryMapper;
import com.springcloud.eshop.inventory.service.ProductInventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.List;

/**
 * (ProductInventory)表服务实现类
 *
 * @author makejava
 * @since 2020-06-29 06:33:23
 */
@Service("productInventoryService")
public class ProductInventoryServiceImpl implements ProductInventoryService {

    /**
     * @Desc: 商品库存redis key前缀
     * @Date: 2020/7/2
     */
    private final static String PRODUCT_INVENTORY_REDIS_KEY_PREFIX = "product_inventory_";

    @Autowired
    private JedisPool jedisPool;

    @Resource
    private ProductInventoryMapper productInventoryMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ProductInventory queryById(Long id) {
        return this.productInventoryMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<ProductInventory> queryAllByLimit(int offset, int limit) {
        return this.productInventoryMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param productInventory 实例对象
     * @return 实例对象
     */
    @Override
    public ProductInventory insert(ProductInventory productInventory) {
        this.productInventoryMapper.insert(productInventory);
        jedisPool.getResource().set(PRODUCT_INVENTORY_REDIS_KEY_PREFIX + productInventory.getProductId(), JSON.toJSONString(productInventory));
        return productInventory;
    }

    /**
     * 修改数据
     *
     * @param productInventory 实例对象
     * @return 实例对象
     */
    @Override
    public ProductInventory update(ProductInventory productInventory) {
        this.productInventoryMapper.update(productInventory);
        jedisPool.getResource().set(PRODUCT_INVENTORY_REDIS_KEY_PREFIX + productInventory.getProductId(), JSON.toJSONString(productInventory));
        return this.queryById(productInventory.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        ProductInventory productInventory = this.productInventoryMapper.queryById(id);
        jedisPool.getResource().del(PRODUCT_INVENTORY_REDIS_KEY_PREFIX + productInventory.getProductId());
        return this.productInventoryMapper.deleteById(id) > 0;
    }
}